<template>
  <ContentWrap>
    <!-- 顶部标签页 -->
    <el-tabs v-model="activeTab" class="mb-4" @tab-change="handleTabChange">
      <el-tab-pane label="跟进记录" name="follow" />
      
      <el-tab-pane label="基本信息" name="basic"/>
        
      <el-tab-pane label="销售订单" name="orders"/>
        
      <el-tab-pane label="产品库" name="products"/>
      <el-tab-pane label="售后跟踪及索赔" name="afterSales"/>
        
    </el-tabs>

    <!-- 跟进记录内容 -->
     <template v-if="activeTab === 'follow'">
    <!-- <div v-if="activeTab === 'follow'"> -->
      <el-row :gutter="20">
        <!-- 左侧列表区域 -->
        <el-col :span="10">
          <div class="flex justify-between items-center mb-4">
            <div>
              <el-button
                type="primary"
                @click="openForm('create')"
                v-hasPermi="['business:cust-follow:create']"
              >
                新增
              </el-button>
              <!-- <el-button
            type="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['business:cust-follow:export']"
          >
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button> -->
            </div>

            <div class="flex items-center">
              <span class="mr-4">共 {{ total }} 条</span>
              <el-button-group>
                <el-button size="small" :disabled="queryParams.pageNo <= 1" @click="prevPage">
                  <Icon icon="ep:arrow-left" />
                </el-button>
                <el-button size="small" disabled
                  >{{ queryParams.pageNo }}/{{ totalPage }}</el-button
                >
                <el-button
                  size="small"
                  :disabled="queryParams.pageNo >= totalPage"
                  @click="nextPage"
                >
                  <Icon icon="ep:arrow-right" />
                </el-button>
              </el-button-group>
            </div>
          </div>
          <!-- 跟进记录列表 -->
          <div class="follow-list">
            <div
              v-for="(item, index) in list"
              :key="item.id"
              class="follow-item mb-4 p-4 border rounded cursor-pointer hover:shadow-md transition-all"
              :class="{ 'border-blue-500 bg-blue-50': activeId === item.id }"
              @click="handleRowClick(item, index)"
            >
              <div class="flex justify-between items-start">
                <div>
                  <div class="font-medium text-gray-800">{{ item.subject }}</div>
                  <!-- <div class="mt-1 text-sm text-gray-500">{{ item.contacts }}</div> -->
                </div>
                <div class="text-xs text-gray-500">
                  {{ formatDate(item.createTime, 'YYYY-MM-DD') }}
                </div>
              </div>

              <div class="mt-2 text-sm">
                <div class="truncate">{{ item.detail }}</div>
              </div>

            </div>
          </div>
        </el-col>

        <!-- 右侧详情区域 -->
        <el-col :span="14">
          <div class="detail-container p-5 border rounded h-full">
            <template v-if="activeFollow">
              <!-- 详情头部 -->
              <div class="flex justify-between items-center mb-6">
                <h3 class="text-lg font-bold">{{ activeFollow.subject }}</h3>
                <div>
                  <el-button
                    plain
                    type="primary"
                    @click="enterEditMode"
                    v-hasPermi="['business:cust-follow:update']"
                    class="mr-2"
                  >
                    编辑
                  </el-button>
                  <el-button
                    plain
                    type="primary"
                    @click="handleDelete(activeFollow.id)"
                    v-hasPermi="['business:cust-follow:delete']"
                  >
                    删除
                  </el-button>
                </div>
              </div>

              <!-- 详情内容 - 查看模式 -->
              <div v-if="!isEditMode">
                <div class="detail-item">
                  <span class="detail-label">跟进人：</span>
                  <span>{{ activeFollow.creator || '未指定' }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">时间：</span>
                  <span>{{ formatDate(activeFollow.createTime) }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">客户阶段：</span>
                  <el-tag type="info">{{ formatStage(activeFollow.stageCode) }}</el-tag>
                </div>
                <div class="detail-item">
                  <span class="detail-label">联系人：</span>
                  <span>{{ activeFollow.contacts }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">跟进主题：</span>
                  <p class="mt-2 whitespace-pre-wrap">{{ activeFollow.subject }}</p>
                </div>

                <div class="detail-item">
                  <span class="detail-label">跟进详情：</span>
                  <p class="mt-2 whitespace-pre-wrap">{{ activeFollow.detail }}</p>
                </div>
                <!-- <div v-if="activeFollow.remark" class="detail-item">
                  <span class="detail-label">备注：</span>
                  <p class="mt-2 whitespace-pre-wrap">{{ activeFollow.remark }}</p>
                </div> -->
              </div>

              <!-- 详情内容 - 编辑模式 -->
              <el-form
                v-else
                ref="editFormRef"
                :model="editForm"
                :rules="editRules"
                label-width="100px"
                class="edit-form"
              >
                <el-form-item label="跟进人">
                  <el-input v-model="activeFollow.creator" disabled />
                </el-form-item>
                <el-form-item label="时间">
                  <el-input :value="formatDate(activeFollow.createTime)" disabled />
                </el-form-item>
                <el-form-item label="客户阶段">
                  <el-select v-model="editForm.stageCode" placeholder="请选择..." class="w-full">
                    <el-option
                      v-for="item in dynamicStageOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="联系人">
                  <el-input v-model="editForm.contacts" placeholder="请输入" />
                </el-form-item>

                <el-form-item label="跟进主题">
                  <el-input v-model="editForm.subject" placeholder="请输入" />
                </el-form-item>

                <el-form-item label="跟进详情">
                  <el-input
                    v-model="editForm.detail"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入"
                  />
                </el-form-item>

                <!-- <el-form-item label="备注">
                  <el-input
                    v-model="editForm.remark"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入"
                  />
                </el-form-item> -->

                <div class="text-right mt-6">
                  <el-button @click="cancelEdit">取消</el-button>
                  <el-button type="primary" @click="saveEdit">保存</el-button>
                </div>
              </el-form>
            </template>

            <!-- 空状态 -->
            <div v-else class="empty-state flex flex-col items-center justify-center h-full">
              <Icon icon="ep:document" class="text-4xl text-gray-300 mb-4" />
              <p class="text-gray-500">请从左侧选择一条跟进记录</p>
            </div>
          </div>
        </el-col>
      </el-row>
    <!-- </div> -->
     </template>

    <!-- 标签页内容 -->
    <component :is="currentTabComponent" v-if="activeTab !== 'follow'" :cust-id="custId.value" />

    <!-- 新增跟进记录弹窗 -->
    <CustFollowForm ref="formRef" @success="handleFormSuccess" />
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { dateFormatter } from '@/utils/formatTime'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import CustFollowForm from './CustFollowForm.vue'
import { CustFollowApi, type CustFollowVO } from '@/api/customermanager/custfollow'
import { formatDate } from '@/utils/formatTime'

import AfterSales from './components/AfterSales.vue'
import SalesOrder from './components/SalesOrder.vue'
import Customer from './components/Customer.vue'
import CustInfoDetail from './components/CustInfoDetail.vue'
import ProductLibrary from './components/ProductLibrary.vue'

// 调用客户阶段接口
import { BaseCustStageApi } from '@/api/business/basecuststage'

const route = useRoute()
const router = useRouter()

// 客户名称
const customerName = ref(String(route.query.cust_name || '当前客户'))

// 客户ID处理 - 更健壮的方式
const custId = computed(() => {
  const id = route.query.cust_id || route.query.custId
  if (!id) return undefined // 返回 undefined 表示没有有效值

  try {
    const numId = Number(id)
    return isNaN(numId) ? undefined : numId // 确保转换为有效的数字
  } catch (e) {
    console.error('无效的客户ID:', id)
    return undefined
  }
})

// 返回客户列表
// const goBack = () => {
//   router.push('/customer_management')
// }
const handleCustomerClick = (customerId) => {
  router.push(`/customermanager/custfollow?cust_id=${customerId}`)
}

// 标签页状态
const activeTab = ref('follow')
const tabLabels = {
  follow: '跟进记录',
  basic: '基本信息',
  orders: '销售订单',
  products: '产品库',
  afterSales: '售后跟踪及索赔'
}

const getTabLabel = (tabName: string) => {
  return tabLabels[tabName as keyof typeof tabLabels] || tabName
}

// 初始化数据
const loading = ref(false)
const exportLoading = ref(false)
const list = ref<CustFollowVO[]>([])
const total = ref(0)
const activeId = ref<number | null>(null)
const activeFollow = ref<CustFollowVO | null>(null)
const activeIndex = ref(0)
const isEditMode = ref(false)

// 分页计算
const totalPage = computed(() => {
  return Math.ceil(total.value / queryParams.pageSize)
})

// 客户阶段选项
const stageOptions = ref([
  { value: 'new_inquiry', label: '新询盘' },
  { value: 'contacted', label: '已联系' },
  { value: 'quoted', label: '已报价' },
  { value: 'negotiation', label: '谈判中' },
  { value: 'closed', label: '已关闭' }
])

// 动态客户阶段选项（从API获取）
const dynamicStageOptions = ref<Array<{value: string, label: string}>>([])

const formatStage = (stageCode: string) => {
  // 处理空值情况
  if (!stageCode) return '未指定'
  // 优先使用动态选项，如果没有则使用静态选项
  const allOptions = [...dynamicStageOptions.value, ...stageOptions.value]
  const stage = allOptions.find((item) => item.value === stageCode)
  return stage ? stage.label : stageCode
}

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5,
  custId: 0
})

// 编辑表单
const editForm = reactive({
  id: 0,
  custId: 0,
  stageCode: '',
  contacts: '',
  subject: '',
  detail: '',
  remark: ''
})

// 获取跟进记录列表
const getList = async () => {
  console.log('请求参数:', queryParams)
  // 确保客户ID有效
  if (queryParams.custId <= 0) {
    console.warn('客户ID无效，跳过获取跟进记录')
    return
  }

  try {
    loading.value = true
    const data = await CustFollowApi.getCustFollowPage(queryParams)
    list.value = data.list || []
    total.value = data.total || 0

    // 如果有记录，默认选中第一条
    if (list.value.length > 0 && !activeId.value) {
      handleRowClick(list.value[0], 0)
    }
  } catch (error) {
    console.error('获取跟进记录失败:', error)
    ElMessage.error('获取跟进记录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取客户阶段选项
const getStageOptions = async () => {
  try {
    const response = await BaseCustStageApi.getAllStage()
    console.log('获取客户阶段数据响应:', response)

    if (response) {
      // 转换格式：{ code: label } → [{ value: code, label }]
      dynamicStageOptions.value = Object.entries(response).map(([value, label]) => ({
        value,
        label: label as string
      }))
    }
  } catch (error) {
    console.error('获取客户阶段失败:', error)
    ElMessage.error('获取客户阶段数据失败')
  }
}

// 点击列表项
const handleRowClick = (row: CustFollowVO, index: number) => {
  console.log('选中记录:', row)
  activeId.value = row.id
  activeFollow.value = { ...row }
  activeIndex.value = index
  isEditMode.value = false
}

// 进入编辑模式
const enterEditMode = async () => {
  if (activeFollow.value) {
    // 在进入编辑模式前先获取最新的阶段选项
    await getStageOptions();

    Object.assign(editForm, {
      id: activeFollow.value.id,
      custId: queryParams.custId,
      stageCode: activeFollow.value.stageCode || '',
      contacts: activeFollow.value.contacts || '',
      subject: activeFollow.value.subject || '',
      detail: activeFollow.value.detail || '',
      remark: activeFollow.value.remark || ''
    })
    isEditMode.value = true
  }
}

// 处理table切换逻辑
const handleTabChange = (tabName: string) => {
  console.log('切换到标签页:', tabName)
}

// 取消编辑
const cancelEdit = () => {
  isEditMode.value = false
}

// 保存编辑
const editFormRef = ref<FormInstance>()
const saveEdit = async () => {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()

    // 更新记录
    await CustFollowApi.updateCustFollow(editForm)
    ElMessage.success('更新成功')

    // 刷新数据
    getList()
    isEditMode.value = false

    // 更新当前选中的记录
    if (activeFollow.value) {
      activeFollow.value = {
        ...activeFollow.value,
        ...editForm
      }
    }
  } catch (error) {
    console.error('更新失败:', error)
  }
}

// 删除记录
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定删除该跟进记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await CustFollowApi.deleteCustFollow(id)
    ElMessage.success('删除成功')

    // 如果是当前选中的记录被删除
    if (activeId.value === id) {
      activeId.value = null
      activeFollow.value = null
    }

    // 重新获取列表
    getList()
  } catch (error) {
    // 用户取消删除
  }
}

// 上一页
const prevPage = () => {
  if (queryParams.pageNo > 1) {
    queryParams.pageNo--
    getList()
  }
}

// 下一页
const nextPage = () => {
  if (queryParams.pageNo < totalPage.value) {
    queryParams.pageNo++
    getList()
  }
}

// 导出记录
const handleExport = async () => {
  try {
    exportLoading.value = true
    await ElMessageBox.confirm('确定导出所有跟进记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    const data = await CustFollowApi.exportCustFollow(queryParams)
    download.excel(data, '客户跟进记录.xls')
  } catch (error) {
    // 用户取消导出
  } finally {
    exportLoading.value = false
  }
}

// 打开新增表单
const formRef = ref()
const openForm = async (type: string) => {
  try {
    const response = await BaseCustStageApi.getAllStage()
    console.log('获取客户阶段数据响应:', response)

    if (!response) {
      console.error('获取客户阶段数据失败')
      ElMessage.error('获取客户阶段数据失败')
      // 传递空数组作为选项
      formRef.value.open(type, null, queryParams.custId, [])
      return
    }

    // 转换格式：{ code: label } → [{ value: code, label }]
    const stages = Object.entries(response).map(([value, label]) => ({
      value,
      label
    }))

    // 正确传递四个参数
    formRef.value.open(type, null, queryParams.custId, stages)
  } catch (error) {
    console.error('获取客户阶段失败:', error)
    ElMessage.error('获取客户阶段数据失败')
    // 传递空数组作为选项
    formRef.value.open(type, null, queryParams.custId, [])
  }
}

// 新增表单提交成功回调
const handleFormSuccess = () => {
  getList()

  // 清空当前选中
  activeId.value = null
  activeFollow.value = null
}

// 页面跳转逻辑
// 需要一个响应式变量来存储客户类型
const customerType = ref('') // 需要在获取客户信息时设置这个值

const currentTabComponent = computed(() => {
  switch (activeTab.value) {
    case 'afterSales':
      return AfterSales
    case 'orders':
      return SalesOrder
    case 'basic':
      // 根据客户类型决定使用哪个组件
      return route.query.type_code === 'company' ? Customer : CustInfoDetail
    case 'products':
      return ProductLibrary
    default:
      return null
  }
})

// 初始化
onMounted(() => {
  console.log('路由参数:', route.query)
  console.log('客户ID:', custId.value)

  // 获取客户阶段选项
  getStageOptions();

  // 如果路由参数中有客户ID，立即加载
  if (custId.value > 0) {
    queryParams.custId = custId.value
    getList()
  } else {
    ElMessage.error('缺少客户ID参数，无法加载跟进记录')
    // 3秒后返回
    setTimeout(() => {
      router.back()
    }, 3000)
  }
})

// 监听客户ID变化 - 放在所有变量声明之后
watch(
  () => custId.value,
  (newVal) => {
    console.log('custId变化:', newVal)
    console.log('queryParams:', queryParams)
    console.log('是否调用getList:', newVal > 0)
    if (newVal > 0) {
      queryParams.custId = newVal
      activeId.value = null
      activeFollow.value = null
      list.value = []
      getList()
    }
  },
  { immediate: true }
)
</script>

<style scoped>
.follow-list {
  max-height: calc(100vh - 280px);
  overflow-y: auto;
}

.follow-item {
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
}

.detail-container {
  min-height: 500px;
  background-color: #fafafa;
}

.detail-item {
  margin-bottom: 18px;
}

.detail-label {
  display: inline-block;
  width: 80px;
  color: #606266;
  font-weight: 500;
}

.empty-state {
  color: #909399;
}

.edit-form {
  max-width: 600px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  height: 50px;
  line-height: 50px;
  padding: 0 20px;
}

:deep(.el-tabs__header) {
  margin: 0;
}

:deep(.el-tabs__nav-wrap)::after {
  height: 1px;
}
</style>
